import {
  Controller,
  Body,
  BadRequestException,
  Post,
  Param,
  Get,
  Query,
  Res,
  Delete,
} from '@nestjs/common';
import { UserService } from './user.service';
import { UpdateUserDto } from './dto/update-user.dto';
import { CreateUserDto } from './dto/create-user.dto';
import { Response } from 'express';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post('apply')
  async apply(@Body() userDto: CreateUserDto | UpdateUserDto) {
    const user = await this.userService.findOne(userDto as UpdateUserDto);
    if (!user) {
      userDto.status = 2;
      userDto.updatedStatusAt = new Date();
      return await this.userService.create(userDto as CreateUserDto);
    }
    if (user.status) {
      return user;
    }
    user.status = 1;
    user.updatedStatusAt = new Date();
    user.category = userDto.category;
    user.works = userDto.works;
    await this.userService.update(user);
    return user;
  }

  @Post(':id/personal')
  async updatePersonalUrl(
    @Param('id') id: string,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    updateUserDto.id = id;
    updateUserDto.updatedPersonalAt = new Date();
    return this.userService.update(updateUserDto);
  }

  @Post(':id/race')
  async updateRaceUrl(
    @Param('id') id: string,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    updateUserDto.id = id;
    updateUserDto.updatedRaceAt = new Date();
    return this.userService.update(updateUserDto);
  }

  @Get('random')
  async getRandomList() {
    return this.userService.findRandomList(100);
  }

  @Get('stats')
  async getStats() {
    return this.userService.getStats();
  }

  @Get('export')
  async export(@Query('date') date: string, @Res() res: Response) {
    const filename = await this.userService.exportDataToExcel(date);
    res.download(filename);
  }

  @Get('apply')
  async getApplyList(
    @Query('pageNo') pageNo: string,
    @Query('pageSize') pageSize: string,
  ) {
    const [list, total] = await this.userService.findApplyList(
      Number(pageNo),
      Number(pageSize),
    );
    return {
      list,
      total,
    };
  }

  @Delete(':id/race')
  async deleteRaceUrl(@Param('id') id: string) {
    return this.userService.deleteRaceUrl(id);
  }
}
